package luj.tool.jnproxyan.proxy.network.https.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.concurrent.EventExecutor;

import java.util.function.Consumer;

final class OutputListenHandler extends ChannelOutboundHandlerAdapter {

  OutputListenHandler(EmbeddedChannel channel, Consumer<ByteBuf> outListener) {
    _channel = channel;
    _outListener = outListener;
  }

  @Override
  public void flush(ChannelHandlerContext ctx) throws Exception {
    EventExecutor exec = ctx.executor();
    exec.submit(() -> triggerListener(exec));

    ctx.flush();
  }

  private void triggerListener(EventExecutor exec) {
    ByteBuf out = _channel.readOutbound();
    if (out == null) {
      return;
    }

    _outListener.accept(out);
    exec.submit(() -> triggerListener(exec));
  }

  private final EmbeddedChannel _channel;

  private final Consumer<ByteBuf> _outListener;
}
